import time, os
from collections import OrderedDict
from django.template import loader
from django.conf import settings

from goods.utils import get_categories
from .models import ContentCategory


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html' % time.ctime())
    # 1. 获取首页中需要的数据

    # 1.1 获取商品分类
    categories = get_categories()
    # categories = {
    #     1: { # 组1
    #         'channels': [{'id':1, 'name':'手机', 'url':''},{'id':2,'name':'数码'}, {}...],
    #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
    #     },
    #     .....
    # 1.2 获取广告数据
    contents = OrderedDict()
    # 获取广告分类
    content_categories = ContentCategory.objects.all()
    # 根据广告分类查询各自的广告内容
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    # cat.content_set获取所有的子类
    # 要写入到模板中的数据
    context = {
        'categories': categories,
        'contents': contents
    }

    # 2. 获取模板
    template = loader.get_template('index.html')
    # 3. 把数据渲染到模板中
    html_text = template.render(context)
    # print(html_text)

    # 4. 把渲染后的数据写到front_end_pc这个前端项目目录的html文件中
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    # print(file_path)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)
